<template>
  <VPage>
    <VTable ref="tableRef" v-bind="tableOptions">
      <template #form="{ form }">
        <VGroup>
          <el-select v-model="form.input.type" style="width: 100px">
            <el-option label="采购单号" value="purchase_no"></el-option>
            <el-option label="开票清单号" value="billing_no"></el-option>
            <el-option label="发票号码" value="invoice_no"></el-option>
          </el-select>
          <VBatchInput v-model="form.input.value" @search="query" class="w-60" />
        </VGroup>
        <VSelect v-model="form.supplier_name" placeholder="供应商" type="supplierName" allow-create style="min-width: 200px" multiple collapse-tags clearable filterable />
        <VGroup>
          <el-select v-model="form.skuInfo.type" class="w-28">
            <el-option label="sku" value="sku"></el-option>
            <el-option label="赛盒SKU" value="sai_he_sku"></el-option>
            <el-option label="自定义sku" value="custom_sku"></el-option>
          </el-select>
          <el-input v-model="form.skuInfo.value" placeholder="请输入" class="w-40"></el-input>
        </VGroup>
        <!-- <VSelect v-model="form.settlement_type" placeholder="结算方式" :options="options.settlement_type" multiple
          collapse-tags style="min-width: 160px" /> -->
        <VCascader v-model="form.department_name" placeholder="部门" type="department" multiple collapse-tags checkStrictly :level="2" style="min-width: 160px" />
        <VCascader v-model="form.purchase_user_id" placeholder="采购人员" multiple collapse-tags style="min-width: 160px" />
        <VSelect v-model="form.company_id" placeholder="公司主体" :options="options.company_id" multiple collapse-tags style="min-width: 210px" />
        <VSelect v-model="form.invoice_status" placeholder="流程状态" :options="options.invoice_status" multiple collapse-tags style="min-width: 160px" />
        <VGroup>
          <div class="v-group-item">审核时间</div>
          <VDate v-model="form.dateRange.value" />
        </VGroup>
      </template>
      <template #toolbar_btns>
        <!-- <VAudit ref="auditRef" auth="/purchase/finance/verification/invoice/audit" field="i_id" url="/v1/finance/invoice/batch-audit" :tableRef="tableRef" @success="query" /> -->
        <VButton auth="/purchase/finance/verification/invoice/audit" :loading="loadings.audit" @click="handleBatch('audit')">批量审核</VButton>
        <VButton auth="/purchase/finance/verification/invoice/print" :loading="loadings.print" @click="handleBatch('print')">批量打印</VButton>
        <!-- <VButton auth="/purchase/finance/verification/invoice/submit" @click="handleBatch('submit')">批量提交</VButton> -->
        <!-- <VButton auth="/purchase/finance/verification/invoice/submit" @click="handleBatch('submit')">批量提交</VButton> -->
        <VButton auth="/purchase/finance/verification/invoice/un_audit" @click="handleBatch('un_audit')">批量反审</VButton>
        <VExport auth="/purchase/finance/verification/invoice/export" mainKey="i_id" :name="baseName" :tableRef="tableRef" class="ml-auto" />
      </template>
    </VTable>
    <Enter ref="enterRef" :api="api" isEdit @success="query" />
    <BatchPrint ref="batchPrintRef" />
    <Audit ref="auditRef" @success="query" :options="options.reject_type"/>
    <VLog ref="logRef" />
  </VPage>
</template>
  
<script setup lang="jsx" name="Account">
import api from './api'
import { getOption } from '@/api/public'
import { ElMessage, ElMessageBox } from 'element-plus'
import BatchPrint from './components/BatchPrint'
import { resMessage } from '@/utils/res'
import Enter from '@/views/finance/verification/billing/components/Enter'
import Audit from './components/Audit'
const baseName = 'invoice'
const tableRef = ref()
const logRef = ref()
const loadings = reactive({})
// 查询
const query = () => {
  tableRef?.value.query()
}

// 获取options
const options = ref({})
Promise.all([
  getOption({ type: baseName }).then(res => res.data),
  getOption({ type: 'payment' }).then(res => res.data),
  // getOption({ type: 'billing' }).then(res => res.data),
  Promise.resolve({ test: [{ label: '没有数据', value: 1 }] })
]).then(res => {
  options.value = res.reduce((acc, cur) => (((acc = { ...acc, ...cur }), acc)), {})
})

// 批量操作
const batchPrintRef = ref()
const handleBatch = (name) => {
  const selection = tableRef.value.$table.getCheckboxRecords()
  if (!selection.length) {
    ElMessage.warning('请先选择行')
    return
  }
  const i_ids = selection.map(d => d.i_id)
  const showLoading = () => loadings[name] = true
  const closeLoading = () => loadings[name] = false
  const handle = {
    print: async () => {
      batchPrintRef?.value.open(i_ids)
    },
    submit: () => {
      showLoading()
      api.submit({ i_ids }).then(res => {
        resMessage({
          res,
          success: () => {
            ElMessage.success('操作成功')
            query()
          }
        })
      }).finally(closeLoading)
    },
    audit: () => {
      auditRef?.value.open(i_ids)
    },
    un_audit:()=>{
      showLoading()
      api.back_invoice({ i_ids }).then(res => {
        resMessage({
          res,
          success: () => {
            ElMessage.success('操作成功')
            query()
          }
        })
      }).finally(closeLoading)
    }
  }
  handle[name]()
}

// 单行操作
const enterRef = ref()
const auditRef = ref()
const handleRow = (name, row, rowIndex) => {
  const { i_id } = row
  const showLoading = () => {
    loadings[name + rowIndex] = true
  }
  const closeLoading = () => {
    loadings[name + rowIndex] = false
  }
  const handle = {
    edit: () => {
      enterRef?.value.open(i_id, row)
    },
    audit: () => {
      auditRef?.value.open([i_id])
    },
    submit: () => {
      showLoading()
      api.submit({ i_ids: [i_id] }).then(res => {
        resMessage({
          res,
          success: () => {
            ElMessage.success('操作成功')
            query()
          }
        })
      }).finally(closeLoading)
    },
    log: () => {
      logRef?.value.open({ log_type: baseName, i_id })
    },
    un_audit:()=>{
      showLoading()
      api.back_invoice({ i_ids: [i_id] }).then(res => {
        resMessage({
          res,
          success: () => {
            ElMessage.success('操作成功')
            query()
          }
        })
      }).finally(closeLoading)
    }
  }
  handle[name]()
}

// 列表配置
const tableOptions = reactive({
  showHeaderOverflow: false,
  formConfig: {
    data: {
      input: { type: 'purchase_no', value: '' },
      skuInfo: { type: 'sku', value: '' },
      dateRange: { type: 'audit_time', value: [], range: true },
    }
  },
  columns: [
    { type: 'checkbox', width: 40, fixed: 'left' },
    { title: '供应商', field: 'supplier_name', minWidth: 140, line: 2 },
    { title: '部门', field: 'department_name', minWidth: 120, line: 2 },
    { title: '采购人员', field: 'purchase_user_name', minWidth: 120, line: 2 },
    { title: '公司主体', field: 'company_id_name', minWidth: 120, line: 2 },
    { title: '发票类型', field: 'invoice_type_name', minWidth: 100 },
    { title: '开票清单号', field: 'billing_no', minWidth: 160 },
    { title: '采购单号', field: 'purchase_no', minWidth: 160 },
    { title: 'SKU', field: 'sku', minWidth: 160 },
    { title: '开票品名', field: 'invoice_name', minWidth: 120, line: 2 },
    { title: '开票单位', field: 'invoice_unit', minWidth: 120, line: 2 },
    { title: '开票不含税单价', field: 'unit_price', minWidth: 100 },
    { title: '发票税率', field: 'tax_percent', minWidth: 100 },
    { title: '发票代码', field: 'invoice_code', minWidth: 100 },
    { title: '发票号码', field: 'invoice_no', minWidth: 100 },
    { title: '发票数量', field: 'invoice_num', minWidth: 100 },
    { title: '开票不含税金额', field: 'total_price', minWidth: 100 },
    { title: '发票行号', field: 'invoice_line', minWidth: 120 },
    { title: '开票日期', field: 'billing_time', minWidth: 120 },
    {
      minWidth: 160, slots: {
        header: () => <div>生成发票人员<br />生成发票时间</div>,
        default: ({ row }) => <div>
          <VText value={row.create_user} />
          <VText value={row.create_time} />
        </div>
      }
    },
    { title: '发票完成时长', field: 'complete_time', minWidth: 160 },
    { title: '流程状态', field: 'invoice_status_name', minWidth: 100 },
    { title: '审核时间', field: 'audit_time', minWidth: 160 },
    { title: '备注', field: 'remark', minWidth: 120, line: 2 },
    {
      title: '操作', width: 180, fixed: 'right', slots: {
        default: ({ row, rowIndex }) => {
          // 发票状态1待提交2待审核3已审核4已驳回
          const { invoice_status } = row
            // {[1, 4].includes(invoice_status) ? <VButton auth="/purchase/finance/verification/invoice/submit" link type="primary" onClick={() => handleRow('submit', row)}>提交</VButton> : ''}
          return <div class='nm flex flex-wrap gap-1'>
            <VButton link type="primary" onClick={() => handleRow('edit', row)}>详情</VButton>
            {[2].includes(invoice_status) ? <VButton auth="/purchase/finance/verification/invoice/audit" link type="primary" onClick={() => handleRow('audit', row)}>审核</VButton> : ''}
            {[3].includes(invoice_status) ? <VButton auth="/purchase/finance/verification/invoice/un_audit" link type="primary" onClick={() => handleRow('un_audit', row)}>反审</VButton> : ''}
            <VButton auth="/purchase/finance/verification/invoice/log" link type="primary" onClick={() => handleRow('log', row)}>日志</VButton>
          </div>
        }
      }
    },
  ],
  proxyConfig: {
    autoLoad: false,
    ajax: {
      query: ({ page, form }) => api.query({ ...form, ...page })
    }
  }
})
</script>
  